const mysql = require('mysql');
const config = require('./config');
const db = {};
const pool = mysql.createPool({
    host     : config.host
    ,port     : config.port
    ,user     : config.user
    ,password : config.password
    ,database : config.database
    ,connectionLimit : 15
});

var exec = function (sql, params, callback) {
    pool.getConnection((err, con) => {
        if (err) {
            throw err;
            callback(err, null, null);
        } else {
            if (params === null || params.length == 0) {
                con.query(sql, function (err, results, fields) {
                    callback(err, results, fields);
                })
            } else {
                con.query(sql, params, function (err, results, fields) {
                    callback(err, results, fields);
                })
            }
            con.release(); //放这
        }
    });

    pool.on('connection',function(){
        console.log('创建一个连接');
    });
         
    //当一个回掉压入队伍等待连接的时候触发入队事件
    pool.on('enqueue',function(){
    　　console.log('入队');
    });
}

db.exec = exec;

module.exports = db;